package com.ComputerSales.controller;


import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ComputerSales.entity.User;
import com.ComputerSales.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 作者
 * @since 2024-06-11
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping("/login")
    public SaResult login(User user) {
        User foundUser = userService.getOne(new QueryWrapper<User>()
                .eq("username", user.getUsername()));
        if (foundUser == null) {
            return SaResult.error("账号不存在！");
        }
        if (foundUser.getPassword().equals(user.getPassword())) {
            StpUtil.login(foundUser.getId());
            StpUtil.getSession().set("role", foundUser.getRole());
            return SaResult.ok();
        } else {
            return SaResult.error("密码错误！");
        }
    }

    @PostMapping("/register")
    public SaResult register(User user) {
        if (user.getPassword().length() < 6) {
            return SaResult.error("密码不得少于6位~");
        }
        if (user.getId() != null) {
            userService.updateById(user);
        } else {
            try {
                userService.save(user);
            } catch (Exception e) {
                return SaResult.error("用户名被占用~");
            }
        }
        return SaResult.ok();
    }

    @PostMapping("/updatePass")
    public SaResult updatePass(@RequestParam String oldPass,@RequestParam String newPass) {
//        检查原密码
        User user = userService.getById(StpUtil.getLoginIdAsInt());
        if (user.getPassword().equals(oldPass)) {
//            更新密码
            user.setPassword(newPass);
            userService.updateById(user);
            return SaResult.ok();
        } else {
            return SaResult.error("原密码输入错误！");
        }
    }




}
